function summonInviteCode(amount) {
    $.get("/user/invite/create?amount=" + amount, r => {
        if (r.success)
            flushInviteCode();
        else
            alert(r.err);
    });
}

function flushInviteCode() {
    $.get("/user/invite/get", r => {
        console.log(r);
        if (!r.success) return alert(r.err);
        $("#invite_code_content").html(r.result.join('<br/>'));
    })
}

function ageSelecterListener(tar) {
    let old = tar.nextSibling.value;
    let ele = '';
    for (let i = (tar.value === '0' ? 1 : 0); i <= 12; i++)
        ele += `<option value='${i}'${i==old?"selected='selected'":''}>${i}个月</option>`;
    $(tar.nextSibling).html(ele);

}

function create_cat_dataSummoner() {
    let x = $("#create_cat_age").parent();
    let date = x.children("input[type='date']").val();
    let isEstimate = x.children('button').hasClass('active');
    let extraObj = x.children('div').children('select');
    let extra = parseInt(extraObj[0].value) * 12 + parseInt(extraObj[1].value);
    let value = toAgeNumber(date, isEstimate, extra);
    $("#create_cat_age").val(value);
}

//加密算法
function encryption(pwd) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.SHA256(pwd));
}

function login_check0() {
    login_check(x => {
        if (x) {
            $("#login").attr('class', 'module l-module');
            $("#login_success").show().siblings().hide();
        } else {
            $("#login").attr('class', 'module b-module');
            $("#login_fail").show().siblings().hide();
        }
        flush_funcContent();
    }, true);
}
//登录
function login(name, pwd) {
    let time = new Date().getTime();
    pwd = encryption(encryption(pwd) + time);
    $.post("/user/auth", { "username": name, "password": pwd, "time": time },
        (result, statue) => {
            if (result.success) localStorage.setItem("token", result.message);
            else {
                alert(result.message);
                console.log(result.message);
            }
            login_check0();
        }
    );
}

let create_cat_data;

function create_cat() {
    $.ajax({
        type: "POST",
        url: "/cats/create",
        cache: 'false',
        data: create_cat_data(),
        beforeSend: req => {
            req.setRequestHeader("x-access-token", localStorage.getItem("token"));
        },
        success: res => {
            if (res.success) {
                alert(`成功创建 ${res.result} 号猫咪!`);
                window.location.href = '/public/cat_info.html?id=' + res.result;
            } else alert(`发生错误:\n${res.error}\n请检查!`);
        }
    });
}

const flush_funcContent = () => {
    $(".functions").children().removeClass('active').hide();
    if (!userInfo.success) return;
    // return;
    let tar = $(window.location.hash);
    if (!(tar.length > 0)) return;
    if (!tar.parents().hasClass('functions')) return;
    tar.addClass('active').show();
};

function getImgs(id, page) {
    $.get(`/img/cats/${id}/${page}`, r => {
        if (!r.success) return alert(`加载失败: ${r.err}`);

        let tar = $("#view_img_content");
        tar.html('');
        for (let x in r.result) {
            x = r.result[x];
            tar.append(`<span class="module img-module"><img src="/img/cat/${x.hash}" /><span>${x.lore}</span></span>`);
        }
    });
}

//上传
function uploadImg() {
    uploadFile('upload_img_select', 'cat-img', req => req.setRequestHeader("x-cat-id", document.getElementById("upload_img_cat").value));
}
let showTableValue = (() => {
    let DATA = {},
        data;
    return (type, value) => {
        DATA[type] = value;
        switch (type) {
            case 'table':
                {
                    let tar = $("#VTV-field_select");
                    tar.html(`<option selected='selected' value=''>空</option>`);
                    if (!(data = nameOfData[DATA.table])) return alert(`出错: 找不到 ${value}表, 目前: ${Object.keys(nameOfData)} `);;
                    for (let key in data) tar.append(`<option value='${key}'>${key}</option>`);
                    break;
                }
            case 'field':
                {
                    let tar = $("#VTV-data_select");
                    tar.html(`<span class="module VTV"><input type="text"><input type="text"><button onclick="VTVchange(this,1);">添加</button></span>`);
                    if (!(data = nameOfData[DATA.table])) return;
                    if (!(data = data[DATA.field])) return alert(`出错: 找不到 ${value}域, 目前: ${Object.keys(nameOfData[DATA.table])}`);;
                    for (let key in data) tar.append(`<span class="module VTV"><input type="text"value="${key}"/><input type="text"value="${data[key]}"/><button onclick="VTVchange(this,0);">保存</button></span>`);
                    break;
                }
        }
    }
})();

function VTVchange(tar, isNew) {
    //TODO 更换table value内容, 此项具有一定风险，后期再完成
}


$(login_check0);
$(() => {
    const old = window.onpopstate;
    window.onpopstate = () => {
        old && old();
        flush_funcContent();
    }
    flush_funcContent();
})